package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"monthtest/cache"
	"monthtest/model"
	"strconv"
	"time"
)

func CarAdd(c *gin.Context) {
	name := c.PostForm("name")
	price, _ := strconv.Atoi(c.PostForm("price"))
	typ := c.PostForm("typ")
	car := model.Car{
		Name:  name,
		Price: price,
		Typ:   typ,
	}
	model.DB.Table("cars").Create(&car)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func OrderAdd(c *gin.Context) {
	customer := c.PostForm("customer")
	cid, _ := strconv.Atoi(c.PostForm("cid"))
	money, _ := strconv.Atoi(c.PostForm("money"))
	data := model.Order{
		Customer: customer,
		Money:    money,
		Cid:      cid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var data []model.CarOrder
	redis_key := "order_list_page" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Table("orders").
			Select("orders.id as Oid",
				"orders.money as Money",
				"orders.customer as Customer",
				"cars.name as Name",
				"cars.price as Price",
				"cars.typ as Typ").
			Joins("left join cars on cars.id = orders.cid").
			Offset(offset).
			Limit(size).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	cid, _ := strconv.Atoi(c.Query("cid"))
	var carorder model.CarOrder
	redis_key := "order_list_page" + strconv.Itoa(cid)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Table("orders").
			Select("orders.id as Oid",
				"orders.money as Money",
				"orders.customer as Customer",
				"cars.name as Name",
				"cars.price as Price",
				"cars.typ as Typ").
			Joins("left join cars on cars.id = orders.cid").
			Where("cars.id = ?").
			Limit(1).
			Find(&carorder)
		jsonData, _ := json.Marshal(&carorder)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &carorder)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": carorder,
	})
}
